/*
 * @Description: 工具
 * @Author: bxsdhx
 * @Date: 2024-02-23 22:22:19
 * @LastEditTime: 2024-12-21 21:42:09
 * Copyright (C) 2024 bxsdhx. All rights reserved.
 */
import { ElMessage } from "element-plus";
import hxzxUtils from "hxzx-utils";
import config from "@/config";
/**
 * @description: 数字相加
 * @return {*}
 */
export const numberAdd = function (...args: number[]): number {
  return args.reduce(function (a, b) {
    return a + b;
  }, 0);
};
/**
 * @description: 复制文本
 * @param {string} text 文本
 * @return {*}
 */
export const copyText = function (text: string): void {
  if (!text) {
    ElMessage.error("无效文本，复制失败");
    return;
  }
  const element = document.createElement("textarea");
  element.style.position = "fixed";
  element.style.top = "-100vh";
  element.setAttribute("readonly", "");
  element.value = text;
  document.body.appendChild(element);
  element.select();
  document.execCommand("copy");
  element.remove();
  ElMessage.success("复制成功");
};
/**
 * @description: 选择文件
 * @param {string} accept 类型
 * @param {number} count 数量
 * @param {number} size 大小，单位B
 * @return {*}
 */
export const choiceFile = function (
  accept: "video" | "audio" | "image",
  count: number = 1,
  size: number = config.uploadImageSize
): Promise<File[]> {
  return new Promise(function (ok) {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = `${accept}/*`;
    input.style.setProperty("position", "fixed");
    input.style.setProperty("top", "-100vh");
    input.oninput = function () {
      if (!input.files || input.files.length === 0) {
        ElMessage.info("未选择任何文件");
        return;
      }
      if (count < input.files.length) {
        ElMessage.info("选择的文件超出数量");
        return;
      }
      for (let i = 0; i < input.files.length; i++) {
        if (input.files[i].size > size) {
          ElMessage.info(
            `选择的文件超出${hxzxUtils.storageConversion(size).auto()}大小限制`
          );
          return;
        }
      }
      ok(input.files as unknown as File[]);
    };
    document.body.appendChild(input);
    input.click();
    input.remove();
  });
};
